package com.kakarote.crm9.erp.jxc.controller;

import com.jfinal.aop.Inject;
import com.jfinal.core.Controller;
import com.jfinal.core.paragetter.Para;
import com.jfinal.plugin.activerecord.Record;
import com.kakarote.crm9.erp.jxc.entity.GoodsUnit;
import com.kakarote.crm9.erp.jxc.service.GoodsUnitService;
import com.kakarote.crm9.utils.BaseUtil;
import com.kakarote.crm9.utils.R;

import java.util.Date;
import java.util.List;

/**
 * @author xjl
 * @date 2021/3/15 16:53
 */
public class GoodsUnitController extends Controller {

    @Inject
    private GoodsUnitService unitService;

    /**
     * 查询所有商品单位
     */
    public void queryList() {
        Integer pageNum = getParaToInt("pageNum", 1);
        Integer pageSize = getParaToInt("pageSize", 10);
        pageNum = (pageNum - 1) * pageSize;
        List<Record> records = unitService.queryList(pageNum, pageSize);
        renderJson(R.ok().put("data", records).put("total", unitService.queryCount().getInt("count")));
    }

    /**
     * 根据id查询
     * @param id
     */
    public void queryId(@Para("id") Integer id) {
        renderJson(R.ok().put("data", unitService.queryById(id)));
    }

    /**
     * 添加
     */
    public void add(@Para("unitName") String unitName) {
        if (unitName == null || unitName.length() <= 0) renderJson(R.error());
        GoodsUnit goodsUnit = new GoodsUnit();
        goodsUnit.setUnitName(unitName);
        goodsUnit.setCreateTime(new Date());
        goodsUnit.setCreateBy(BaseUtil.getUser().getUsername());
        renderJson(unitService.insertUnit(goodsUnit));
    }

    /**
     * 更新
     * @param goodsUnit
     */
    public void update(@Para("") GoodsUnit goodsUnit) {
        if (goodsUnit == null) renderJson(R.error());
        renderJson(unitService.updateUnit(goodsUnit));
    }

    /**
     * 删除
     */
    public void delete(@Para("ids") String ids) {
        if (ids == null || ids.length() <= 0) renderJson(R.error());
        if (ids.contains(",")) {
            String[] split = ids.split(",");
            int[] params = new int[split.length];
            for (int i = 0; i < split.length; i++) {
                params[i] = Integer.parseInt(split[i]);
            }
            renderJson(unitService.deleteUnit(params));
        } else {
            renderJson(unitService.deleteUnit(new int[] { Integer.parseInt(ids) }));
        }

    }
}
